const express = require('express');
const { body, validationResult } = require('express-validator');
const { query } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;

const router = express.Router();

// 配置multer用于文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = path.join(__dirname, '../../uploads/chat');
    // 确保目录存在
    if (!require('fs').existsSync(uploadPath)) {
      require('fs').mkdirSync(uploadPath, { recursive: true });
    }
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024 // 10MB限制
  }
});

// 获取聊天室列表
router.get('/rooms', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;

    const rooms = await query(`
      SELECT 
        cr.id,
        CASE 
          WHEN cr.room_type = 'private' THEN (
            SELECT u.username 
            FROM chat_room_members crm2 
            JOIN users u ON crm2.user_id = u.id 
            WHERE crm2.room_id = cr.id AND crm2.user_id != ?
          )
          ELSE cr.name
        END as name,
        cr.room_type,
        cr.description,
        cr.avatar,
        cr.created_at,
        cr.updated_at,
        crm.last_read_at,
        (
          SELECT content 
          FROM chat_messages cm 
          WHERE cm.room_id = cr.id 
          ORDER BY cm.created_at DESC 
          LIMIT 1
        ) as last_message,
        (
          SELECT created_at 
          FROM chat_messages cm 
          WHERE cm.room_id = cr.id 
          ORDER BY cm.created_at DESC 
          LIMIT 1
        ) as last_message_time,
        (
          SELECT COUNT(*) 
          FROM chat_messages cm 
          WHERE cm.room_id = cr.id 
            AND cm.created_at > crm.last_read_at
            AND cm.sender_id != ?
        ) as unread_count
      FROM chat_rooms cr
      JOIN chat_room_members crm ON cr.id = crm.room_id
      WHERE crm.user_id = ? AND cr.is_active = true
      ORDER BY last_message_time DESC, cr.updated_at DESC
    `, [userId, userId, userId]);

    res.json({ success: true, rooms });
  } catch (error) {
    console.error('获取聊天室列表失败:', error);
    res.status(500).json({ success: false, message: '获取聊天室列表失败' });
  }
});

// 创建私聊
router.post('/private', authenticateToken, [
  body('friend_id').isInt().withMessage('好友ID必须是整数')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const userId = req.user.id;
    const { friend_id } = req.body;

    // 检查是否是好友
    const friendship = await query(`
      SELECT id FROM friendships 
      WHERE (user_id = ? AND friend_id = ? AND status = 'accepted') 
         OR (user_id = ? AND friend_id = ? AND status = 'accepted')
    `, [userId, friend_id, friend_id, userId]);

    if (friendship.length === 0) {
      return res.status(400).json({ success: false, message: '只能与好友创建私聊' });
    }

    // 检查是否已存在私聊
    const existingRoom = await query(`
      SELECT cr.id 
      FROM chat_rooms cr
      JOIN chat_room_members crm1 ON cr.id = crm1.room_id
      JOIN chat_room_members crm2 ON cr.id = crm2.room_id
      WHERE cr.room_type = 'private' 
        AND crm1.user_id = ? AND crm2.user_id = ?
    `, [userId, friend_id]);

    if (existingRoom.length > 0) {
      return res.json({ success: true, room_id: existingRoom[0].id, message: '私聊已存在' });
    }

    // 创建私聊
    const roomResult = await query(`
      INSERT INTO chat_rooms (room_type, created_by) 
      VALUES ('private', ?)
    `, [userId]);

    const roomId = roomResult.insertId;

    // 添加成员
    await query(`
      INSERT INTO chat_room_members (room_id, user_id, role) 
      VALUES (?, ?, 'member'), (?, ?, 'member')
    `, [roomId, userId, roomId, friend_id]);

    res.json({ success: true, room_id: roomId, message: '私聊创建成功' });
  } catch (error) {
    console.error('创建私聊失败:', error);
    res.status(500).json({ success: false, message: '创建私聊失败' });
  }
});

// 创建群聊
router.post('/group', authenticateToken, [
  body('name').notEmpty().withMessage('群聊名称不能为空'),
  body('description').optional(),
  body('member_ids').isArray().withMessage('成员ID必须是数组')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const userId = req.user.id;
    const { name, description, member_ids } = req.body;

    // 创建群聊
    const roomResult = await query(`
      INSERT INTO chat_rooms (name, room_type, created_by, description) 
      VALUES (?, 'group', ?, ?)
    `, [name, userId, description || null]);

    const roomId = roomResult.insertId;

    // 添加创建者为管理员
    await query(`
      INSERT INTO chat_room_members (room_id, user_id, role) 
      VALUES (?, ?, 'admin')
    `, [roomId, userId]);

    // 添加其他成员
    if (member_ids && member_ids.length > 0) {
      const memberValues = member_ids.map(memberId => [roomId, memberId, 'member']);
      for (const [room_id, user_id, role] of memberValues) {
        await query(`
          INSERT INTO chat_room_members (room_id, user_id, role) 
          VALUES (?, ?, ?)
        `, [room_id, user_id, role]);
      }
    }

    res.json({ success: true, room_id: roomId, message: '群聊创建成功' });
  } catch (error) {
    console.error('创建群聊失败:', error);
    res.status(500).json({ success: false, message: '创建群聊失败' });
  }
});

// 获取聊天室成员
router.get('/rooms/:id/members', authenticateToken, async (req, res) => {
  try {
    const roomId = req.params.id;
    const userId = req.user.id;

    // 检查用户是否是聊天室成员
    const membership = await query(`
      SELECT id FROM chat_room_members 
      WHERE room_id = ? AND user_id = ?
    `, [roomId, userId]);

    if (membership.length === 0) {
      return res.status(403).json({ success: false, message: '无权访问此聊天室' });
    }

    const members = await query(`
      SELECT 
        u.id,
        u.username,
        u.avatar,
        u.is_online,
        crm.role,
        crm.joined_at,
        crm.last_read_at
      FROM chat_room_members crm
      JOIN users u ON crm.user_id = u.id
      WHERE crm.room_id = ?
      ORDER BY crm.role DESC, crm.joined_at ASC
    `, [roomId]);

    res.json({ success: true, members });
  } catch (error) {
    console.error('获取聊天室成员失败:', error);
    res.status(500).json({ success: false, message: '获取聊天室成员失败' });
  }
});

// 获取聊天消息
router.get('/rooms/:id/messages', authenticateToken, async (req, res) => {
  try {
    const roomId = req.params.id;
    const userId = req.user.id;
    const { page = 1, limit = 50 } = req.query;

    // 检查用户是否是聊天室成员
    const membership = await query(`
      SELECT id FROM chat_room_members 
      WHERE room_id = ? AND user_id = ?
    `, [roomId, userId]);

    if (membership.length === 0) {
      return res.status(403).json({ success: false, message: '无权访问此聊天室' });
    }

    const offset = (page - 1) * limit;

    const messages = await query(`
      SELECT 
        cm.id,
        cm.sender_id,
        cm.message_type,
        cm.content,
        cm.file_url,
        cm.file_name,
        cm.file_size,
        cm.reply_to,
        cm.created_at,
        u.username as sender_name,
        u.avatar as sender_avatar,
        reply_msg.content as reply_content,
        reply_user.username as reply_sender_name
      FROM chat_messages cm
      JOIN users u ON cm.sender_id = u.id
      LEFT JOIN chat_messages reply_msg ON cm.reply_to = reply_msg.id
      LEFT JOIN users reply_user ON reply_msg.sender_id = reply_user.id
      WHERE cm.room_id = ? AND cm.is_deleted = false
      ORDER BY cm.created_at DESC
      LIMIT ? OFFSET ?
    `, [roomId, parseInt(limit), offset]);

    // 更新最后阅读时间
    await query(`
      UPDATE chat_room_members 
      SET last_read_at = NOW() 
      WHERE room_id = ? AND user_id = ?
    `, [roomId, userId]);

    res.json({ success: true, messages: messages.reverse() });
  } catch (error) {
    console.error('获取聊天消息失败:', error);
    res.status(500).json({ success: false, message: '获取聊天消息失败' });
  }
});

// 发送消息
router.post('/rooms/:id/messages', authenticateToken, [
  body('content').notEmpty().withMessage('消息内容不能为空'),
  body('message_type').optional().isIn(['text', 'image', 'file']).withMessage('消息类型无效'),
  body('reply_to').optional().isInt().withMessage('回复消息ID必须是整数')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const roomId = req.params.id;
    const userId = req.user.id;
    const { content, message_type = 'text', reply_to, file_url, file_name, file_size } = req.body;

    // 检查用户是否是聊天室成员
    const membership = await query(`
      SELECT id FROM chat_room_members 
      WHERE room_id = ? AND user_id = ?
    `, [roomId, userId]);

    if (membership.length === 0) {
      return res.status(403).json({ success: false, message: '无权在此聊天室发送消息' });
    }

    // 发送消息
    const messageResult = await query(`
      INSERT INTO chat_messages 
      (room_id, sender_id, message_type, content, file_url, file_name, file_size, reply_to) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `, [roomId, userId, message_type, content, file_url || null, file_name || null, file_size || null, reply_to || null]);

    const messageId = messageResult.insertId;

    // 更新聊天室最后更新时间
    await query(`
      UPDATE chat_rooms 
      SET updated_at = NOW() 
      WHERE id = ?
    `, [roomId]);

    res.json({ success: true, message_id: messageId, message: '消息发送成功' });
  } catch (error) {
    console.error('发送消息失败:', error);
    res.status(500).json({ success: false, message: '发送消息失败' });
  }
});

// 删除消息
router.delete('/messages/:id', authenticateToken, async (req, res) => {
  try {
    const messageId = req.params.id;
    const userId = req.user.id;

    // 检查消息是否存在且发送者是当前用户
    const message = await query(`
      SELECT id, sender_id FROM chat_messages 
      WHERE id = ? AND sender_id = ?
    `, [messageId, userId]);

    if (message.length === 0) {
      return res.status(404).json({ success: false, message: '消息不存在或无权限删除' });
    }

    // 软删除消息
    await query(`
      UPDATE chat_messages 
      SET is_deleted = true 
      WHERE id = ?
    `, [messageId]);

    res.json({ success: true, message: '消息已删除' });
  } catch (error) {
    console.error('删除消息失败:', error);
    res.status(500).json({ success: false, message: '删除消息失败' });
  }
});

// 添加群聊成员
router.post('/rooms/:id/members', authenticateToken, [
  body('user_ids').isArray().withMessage('用户ID必须是数组')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const roomId = req.params.id;
    const userId = req.user.id;
    const { user_ids } = req.body;

    // 检查用户是否是群聊管理员
    const membership = await query(`
      SELECT role FROM chat_room_members 
      WHERE room_id = ? AND user_id = ? AND role = 'admin'
    `, [roomId, userId]);

    if (membership.length === 0) {
      return res.status(403).json({ success: false, message: '只有管理员可以添加成员' });
    }

    // 添加成员
    for (const memberId of user_ids) {
      await query(`
        INSERT INTO chat_room_members (room_id, user_id, role) 
        VALUES (?, ?, 'member')
        ON DUPLICATE KEY UPDATE role = 'member'
      `, [roomId, memberId]);
    }

    res.json({ success: true, message: '成员添加成功' });
  } catch (error) {
    console.error('添加群聊成员失败:', error);
    res.status(500).json({ success: false, message: '添加群聊成员失败' });
  }
});

// 移除群聊成员
router.delete('/rooms/:id/members/:memberId', authenticateToken, async (req, res) => {
  try {
    const roomId = req.params.id;
    const memberId = req.params.memberId;
    const userId = req.user.id;

    // 检查用户是否是群聊管理员
    const membership = await query(`
      SELECT role FROM chat_room_members 
      WHERE room_id = ? AND user_id = ? AND role = 'admin'
    `, [roomId, userId]);

    if (membership.length === 0) {
      return res.status(403).json({ success: false, message: '只有管理员可以移除成员' });
    }

    // 移除成员
    await query(`
      DELETE FROM chat_room_members 
      WHERE room_id = ? AND user_id = ?
    `, [roomId, memberId]);

    res.json({ success: true, message: '成员移除成功' });
  } catch (error) {
    console.error('移除群聊成员失败:', error);
    res.status(500).json({ success: false, message: '移除群聊成员失败' });
  }
});

// 删除聊天室
router.delete('/rooms/:id', authenticateToken, async (req, res) => {
  try {
    const roomId = req.params.id;
    const userId = req.user.id;

    // 检查用户是否是聊天室成员
    const membership = await query(
      'SELECT * FROM chat_room_members WHERE room_id = ? AND user_id = ?',
      [roomId, userId]
    );

    if (membership.length === 0) {
      return res.status(403).json({ success: false, message: '无权限删除此聊天室' });
    }

    // 对于私聊，直接删除聊天室
    // 对于群聊，检查是否是管理员
    const room = await query('SELECT * FROM chat_rooms WHERE id = ?', [roomId]);
    if (room.length === 0) {
      return res.status(404).json({ success: false, message: '聊天室不存在' });
    }

    if (room[0].room_type === 'group') {
      // 群聊需要管理员权限
      const member = await query(
        'SELECT role FROM chat_room_members WHERE room_id = ? AND user_id = ?',
        [roomId, userId]
      );
      
      if (member.length === 0 || member[0].role !== 'admin') {
        return res.status(403).json({ success: false, message: '只有管理员可以删除群聊' });
      }
    }

    // 删除聊天室（级联删除相关数据）
    await query('DELETE FROM chat_rooms WHERE id = ?', [roomId]);

    res.json({ success: true, message: '聊天室删除成功' });
  } catch (error) {
    console.error('删除聊天室失败:', error);
    res.status(500).json({ success: false, message: '删除聊天室失败' });
  }
});

// 发送文件
router.post('/rooms/:id/messages/file', authenticateToken, upload.single('file'), async (req, res) => {
  try {
    const roomId = req.params.id;
    const userId = req.user.id;

    // 检查用户是否是聊天室成员
    const membership = await query(`
      SELECT id FROM chat_room_members 
      WHERE room_id = ? AND user_id = ?
    `, [roomId, userId]);

    if (membership.length === 0) {
      return res.status(403).json({ success: false, message: '无权访问此聊天室' });
    }

    // 检查是否有文件上传
    if (!req.file) {
      return res.status(400).json({ success: false, message: '没有上传文件' });
    }

    const file = req.file;
    // 处理文件名编码问题
    const fileName = Buffer.from(file.originalname, 'latin1').toString('utf8');
    const fileSize = file.size;
    const fileType = file.mimetype;
    const fileUrl = `/uploads/chat/${file.filename}`;

    // 保存消息到数据库
    const result = await query(`
      INSERT INTO chat_messages (room_id, sender_id, message_type, content, file_url, file_name, file_size, created_at)
      VALUES (?, ?, 'file', ?, ?, ?, ?, NOW())
    `, [roomId, userId, fileName, fileUrl, fileName, fileSize]);

    res.json({ 
      success: true, 
      message: '文件发送成功',
      message_id: result.insertId,
      file_url: fileUrl
    });
  } catch (error) {
    console.error('发送文件失败:', error);
    res.status(500).json({ success: false, message: '发送文件失败' });
  }
});

// 下载文件
router.get('/files/:filename', authenticateToken, async (req, res) => {
  try {
    const filename = req.params.filename;
    const filePath = path.join(__dirname, '../../uploads/chat', filename);
    
    // 检查文件是否存在
    try {
      await fs.access(filePath);
    } catch (error) {
      return res.status(404).json({ success: false, message: '文件不存在' });
    }
    
    // 设置下载头，处理中文文件名
    const encodedFilename = encodeURIComponent(filename);
    res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodedFilename}`);
    res.setHeader('Content-Type', 'application/octet-stream');
    
    // 发送文件
    res.sendFile(filePath);
  } catch (error) {
    console.error('下载文件失败:', error);
    res.status(500).json({ success: false, message: '下载文件失败' });
  }
});

module.exports = router;